package com.ruoyi.uni.util;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@ConfigurationProperties(prefix = "wx")
@PropertySource("classpath:wxConfig.yml")
public class wxRequestUtil {
    @Value("${appid}")
    public  String appid;

    @Value("${secret}")
    public String secret;


    @Value("${url}")
    public String url;

    @Value("${envVersion}")
    public String envVersion;

    @Autowired
    private RestTemplate restTemplate;
    public JSONObject getWxLoginReq(String jsCode){
        String Url=url+"/sns/jscode2session?appid={appid}&secret={secret}&js_code={jsCode}&grant_type=authorization_code";
        ResponseEntity<String> forEntity = restTemplate.getForEntity(Url, String.class,appid,secret,jsCode);
        return JSONObject.parseObject(forEntity.getBody());
    }
    public byte[] postWxQRCodeReq(String path,int width){
        String token = postWxAccessToken().getString("access_token");
        String Url=url+"/wxa/getwxacode?access_token="+token;
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("path",path);
        jsonObject.put("width",width);
        jsonObject.put("env_version",envVersion);
        ResponseEntity<byte[]> responseEntity = restTemplate.postForEntity(Url, jsonObject, byte[].class);
       return  responseEntity.getBody();
    }

    private JSONObject postWxAccessToken(){
        String Url=url+"/cgi-bin/stable_token";
        JSONObject param=new JSONObject();
        param.put("grant_type","client_credential");
        param.put("appid",appid);
        param.put("secret",secret);
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(Url, param, String.class);
        return JSONObject.parseObject(stringResponseEntity.getBody());
    }
}
